package com.jack.lib.core.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2020-04-06
 * desc   :
 */
public class ObjectUtils {


    public static void formatNull(Object o){

        Class<?> aClass = o.getClass();
        Field[] fields = aClass.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);


           if (Modifier.isStatic(field.getModifiers())){
               continue;
           }
            if (field.getType() == String.class) {
                formatStringForNull(field, o);

            }else if (field.getGenericType() instanceof ParameterizedType){

                Type genericType = field.getGenericType();

                ParameterizedType parameterizedType = (ParameterizedType)genericType;
                Type[] actualTypes = parameterizedType.getActualTypeArguments();
                if (actualTypes[0] == String.class) {
                    formatListStringForNull(field, o);
                }else {
                    formatListObjForNull(field, o);
                }
            }

        }

    }

    private static void formatStringForNull(Field field, Object o){
        try {
            if (field.get(o) == null) {
                field.set(o, "");
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private static void formatListStringForNull(Field field, Object o){
        try {
            if (field.get(o) == null) {
                field.set(o, new ArrayList<>());
            }else {
                List list = (List) field.get(o);
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i) == null) {
                        list.set(i, "");
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private static void formatListObjForNull(Field field, Object o){
        try {
            if (field.get(o) == null) {
                field.set(o, new ArrayList<>());
            }else {

                List list = (List) field.get(o);
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i) != null) {
                        formatNull(list.get(i));
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


}
